<template>
  <el-dialog
    :title="title"
    :width="width"
    top="50px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible.sync="isVisible"
  >
    <div v-for="i in row.inputType.length" :key="i">
      <el-form ref="form" :model="row" label-position="top" label-width="125px">
        <el-form-item
          v-if="row.inputType[i-1].lavValue==='单选'"
          class="enum_1"
          :label="row.enumValue[i-1]"
          :prop="'awardInformations['+(i-1)+'].aiValue'"
          :rules="[{ required: true, message: '请选择', trigger: 'blur,change' }]"
        >
          <el-select
            v-model="row.awardInformations[i-1].aiValue"
            :placeholder="'请选择' + row.enumValue[i-1]"
          >
            <el-option
              v-for="{rChildrenName, rIndex} in row.relations[i-1]"
              :key="rIndex"
              :label="rChildrenName"
              :value="rChildrenName"
            />
          </el-select>
        </el-form-item>
        <!--日期-->
        <el-form-item
          v-if="row.inputType[i-1].lavValue==='日期'"
          :label="row.enumValue[i-1]"
          :prop="'awardInformations['+(i-1)+'].aiValue'"
          :rules="[{ required: true, message: '请选择日期。', trigger: 'blur,change' }]"
        >
          <el-date-picker
            v-model="row.awardInformations[i-1].aiValue"
            type="date"
            placeholder="请补充日期！"
            style="width: 70%"
            value-format="yyyyMMdd"
          />
        </el-form-item>
        <!--附件-->
        <el-form-item
          v-if="row.inputType[i-1].lavValue==='附件'"
          class="attachment_3"
          :label="row.enumValue[i-1]"
          :prop="'awardInformations['+(i-1)+'].aiValue'"
          :rules="[{ required: true, message: '请上传附件。', trigger: 'blur,change' }]"
        >
          <el-upload
            ref="uploads"
            :auto-upload="false"
            :action="uploadAction"
            :headers="headers"
            accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.PNG,.GIF,.BMP,.pdf,.PDF"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-change="onfileChange"
            :on-exceed="handleExceed"
            :http-request="uploadFile"
            multiple
            :limit="1"
            :file-list="row.fileList"
            list-type="picture"
          >
            <el-button size="small">点击上传</el-button> <!-- type="primary"-->
            <span slot="tip" class="el-upload__tip">请上传图片/PDF格式文件，且大小不超过10MB！</span>
          </el-upload>
        </el-form-item>
        <!--输入框-->
        <el-form-item
          v-if="row.inputType[i-1].lavValue==='纯文本'"
          class="input_4"
          :label="row.enumValue[i-1]"
          :prop="'awardInformations['+(i-1)+'].aiValue'"
          :rules="[{ required: true, message: '请按照提示输入。', trigger: 'blur,change' }]"
        >
          <el-input
            v-model="row.awardInformations[i-1].aiValue"
            :placeholder="defaultWords[i-1]"
            style="width: 400px"
            @change="row.enumValue[i-1]==='期刊名称'?fetchpsPublicationName(row.awardInformations[i-1].aiValue):''"
          />
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="warning" plain @click="isVisible = false">
        {{ $t('common.cancel') }}
      </el-button>
      <el-button type="primary" plain :loading="buttonLoading" @click="submitUpload">
        {{ $t('common.confirm') }}
      </el-button>
    </div>
    <el-dialog :visible.sync="filedialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </el-dialog>
</template>
<script>
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import axios from 'axios'
import { getToken } from '@/utils/auth'

export default {
  name: 'UserEdit',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 原有数据
      buttonLoading: false,
      screenWidth: 0,
      width: this.initWidth(),
      // 【新数据】
      // 验证ISSN期刊名称和表单必填项
      flagUpload: false,
      flagISSN: true,
      flagValid: false,
      // 用于证明文件提交
      uploadAction: '/api/achievement/award/insertAAnnex',
      dialogImageUrl: '',
      filedialogVisible: false,
      // row用于获取某行信息
      row: {
        fileList: [],
        inputType: [],
        enumValue: [],
        awardInformations: [],
        relations: []
      }
    }
  },
  computed: {
    isVisible: {
      get() {
        return this.dialogVisible
      },
      set() {
        this.close()
        this.reset()
      }
    },
    headers: function() {
      return { Authorization: 'bearer ' + getToken() }
    },
    defaultWords: function() {
      const words = []
      for (let i = 0; i < this.row.inputType.length; i++) {
        words[i] = this.row.enumValue[i] === '期刊名称' ? '输入出版物 ISSN (格式：xxxx-xxxx )' : '输入' + this.row.enumValue[i]
      }
      return words
    }
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.width = this.initWidth()
      })()
    }
  },
  methods: {
    // [新增功能如下]
    // setIndexs函数拿到接口2的返回值
    setIndexs(row) {
      row.fileList = row.awardInformations[row.enumValue.indexOf('证明材料（附件）')].aiValue !== '' ? [{ name: row.awardInformations[row.enumValue.indexOf('证明材料（附件）')].aiValue.slice(26), url: row.awardInformations[row.enumValue.indexOf('证明材料（附件）')].aiValue }] : []
      this.row = { ...row }
      console.log(this.row)
    },
    // 通过ISSN获取期刊名称 触发方式v-on=change 成功则期刊名称绑定给ai-value，flagISSN为false； 失败则弹框。aiValue为用户输入值 flagISSN为false
    fetchpsPublicationName(value) {
      // 只要有期刊名称接口的情况 先赋值为FLASE
      this.flagISSN = false
      this.$get('achievement/award/queryPeriodicalByISSN', {
        psISSN: value
      }).then((r) => {
        if (r.data.data) {
          this.flagISSN = true
          this.row.awardInformations[this.row.enumValue.indexOf('期刊名称')].aiValue = r.data.data.psPublicationName
          this.$message({
            message: 'ISSN至期刊名称转换成功',
            type: 'success'
          })
        } else {
          this.flagISSN = false
          this.$alert('暂未获取对应出版物，请检查ISSN。若仍有问题，请联系辅导员处理。', 'ISSN读取失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.$message.error('暂未获取对应出版物，请检查ISSN')
            }
          })
          // this.form.attrsList[this.label.indexOf('期刊名称')].aiValue = '请检查ISSN是否正确，如有问题，联系辅导员。'
        }
      })
    },
    // 用于文件传输
    submitUpload() {
      if (this.row.enumValue.indexOf('证明材料（附件）') !== -1 && this.flagUpload) {
        this.$refs.uploads[0].submit()
      } else {
        for (let h = 0; h < this.row.inputType.length; h++) {
          this.$refs.form[h].validate((valid) => {
            if (valid) {
              this.flagValid = valid
            } else {
              this.flagValid = valid
            }
            return valid
          })
          if (this.flagValid === false) { break }
        }
        // 根据两个flag内容确定是否发出POST请求
        if (this.flagValid && this.flagISSN) {
          this.buttonLoading = true
          // axios Post方法 其中body中的数据赋给data
          axios({
            method: 'post',
            url: '/api/achievement/award/updateStuAwardAttr',
            headers: { Authorization: 'bearer ' + getToken() },
            data: this.row.awardInformations
          })
            .then((r) => {
              this.buttonLoading = false
              this.isVisible = false
              console.log(r.data)
              // window.open('/#/student/see_awards', '_self'),
              this.reset()
              this.$message({
                message: this.$t('tips.updateSuccess'),
                type: 'success'
              })
            })
            .catch(function(error) { // 请求失败处理
              console.log('请求失败!具体信息如下:')
              console.log(error)
            })
        } else {
          this.$message.error('请按照规则填写表单')
          return false
        }
      }
    },
    uploadFile(content) {
      const form = new FormData()
      form.append('file', content.file)
      this.buttonLoading = true
      axios({
        method: 'post',
        url: '/api/achievement/award/insertAAnnex',
        headers: { Authorization: 'bearer ' + getToken() },
        data: form,
        params: { id: this.row.inputType[this.row.enumValue.indexOf('证明材料（附件）')].aaIndex }
      }).then(res => {
        console.log('file post success')
        this.row.awardInformations[this.row.enumValue.indexOf('证明材料（附件）')].aiValue = res.data.data.annexPath
        if (res.data.code !== 200) {
          content.onError('文件上传失败, code:' + res.data.code)
          this.buttonLoading = false
        } else {
          content.onSuccess('文件上传成功！')
        }
        // for循环开始，判断每个form是否合规
        for (let h = 0; h < this.row.inputType.length; h++) {
          // 根据验证结果给flag赋值
          this.$refs.form[h].validate((valid) => {
            if (valid) {
              this.flagValid = valid
            } else {
              this.flagValid = valid
            }
            return valid
          })
          if (this.flagValid === false) { break }
        }
        // 根据两个flag内容确定是否发出POST请求
        if (this.flagValid && this.flagISSN) {
          console.log('this.row.awardInformations')
          console.log(this.row.awardInformations)
          axios({
            method: 'post',
            url: '/api/achievement/award/updateStuAwardAttr',
            headers: { Authorization: 'bearer ' + getToken() },
            data: this.row.awardInformations
          }).then((r) => {
            console.log(r)
            this.buttonLoading = false
            this.isVisible = false
            this.$message({
              message: this.$t('tips.createSuccess'),
              type: 'success'
            })
            window.open('/#/student/see_awards', '_self')
            this.reset()
            this.$message({
              message: '提交成功',
              type: 'success'
            })
          })
            .catch(function(error) { // 请求失败处理
              console.log(error)
            })
        } else {
          this.$message.error('你不好好填写上传个锤子，按照规则把表单内容填完整啦')
          return false
        }
      }).catch(error => {
        console.log('file post success')
        this.buttonLoading = false
        console.log(error.response)
        if (error.response) {
          content.onError('文件上传失败,' + error.response.data)
        } else if (error.request) {
          content.onError('文件上传失败，服务器端无响应')
        } else {
          content.onError('文件上传失败，请求封装失败')
        }
      })
    },
    // 限制文件的大小，限制文件的类型
    onfileChange(file) {
      console.log('onfileChange')
      this.flagUpload = false
      const isJPG = file.raw.type === 'image/png' || file.raw.type === 'image/jpg' || file.raw.type === 'image/jpeg' || file.raw.type === 'image/gif' || file.raw.type === 'image/bmp' || file.raw.type === 'image/JPG' || file.raw.type === 'image/JPEG' || file.raw.type === 'image/GIF' || file.raw.type === 'image/BMP' || file.raw.type === 'application/pdf'
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isJPG) {
        this.$message.error('证明材料仅允许 pdf/jpg/jpeg/png/gif/bmp 格式!请重新选取')
      }
      if (!isLt10M) {
        this.$message.error('证明材料大小不能超过 10MB!请删除当前附件重新选取')
      }
      if (isJPG && isLt10M) {
        console.log('改寫fileList')
        this.row.fileList = []
        this.row.fileList.push(file)
      }
      console.log(this.row.fileList)
      this.flagUpload = isLt10M && isJPG
      return isJPG && isLt10M
    },
    // 限制文件的数量
    handleExceed() {
      // this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      this.$message.warning(`当前限制选择 1 个文件`)
    },
    // 预览函数
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.filedialogVisible = true
    },
    // 删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 则停止删除。
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 文件列表移除文件时的钩子 在文件移除列表时，同时删除对应aiValue和filelist内容 参数可以为file,filelist
    handleRemove() {
      this.flagUpload = false
    },
    // 以下为原有功能
    initWidth() {
      this.screenWidth = document.body.clientWidth
      if (this.screenWidth < 991) {
        return '90%'
      } else if (this.screenWidth < 1400) {
        return '45%'
      } else {
        return '800px'
      }
    },
    close() {
      this.$emit('close')
    },
    reset() {
      this.flagISSN = true
      return 0
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
